<template>
	<!-- 面包屑 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{path:'/welcome'}">首页</el-breadcrumb-item>
		<el-breadcrumb-item>权限管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 行内表单 -->
	<el-form :inline="true" :model="formInline" class="demo-form-inline">
		<el-form-item label="权限名称">
			<el-input v-model="formInline.name" placeholder="请输入权限名称" clearable @clear="query" />
		</el-form-item>
		<el-form-item label="权限类型">
			<el-select v-model="formInline.type" placeholder="请选择权限类型">
				<el-option label="类型1" value="1"></el-option>
				<el-option label="类型2" value="2"></el-option>
				<el-option label="类型3" value="3"></el-option>
			</el-select>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="seek">搜索</el-button>
			<el-button type="primary" @click="dialogVisible = true">新增权限</el-button>
			<el-button type="danger" @click="removeAll">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 新增权限弹出框 -->
	<el-dialog v-model="dialogVisible" :title="title" width="500" @close="cancle">
		<el-form :model="form" label-width="auto" style="max-width: 600px">
			<el-form-item label="权限名称">
				<el-input v-model="form.name" placeholder="请输入权限名称" />
			</el-form-item>
			<el-form-item label="权限类型">
				<el-select v-model="form.type">
					<el-option label="类型1" value="1"></el-option>
					<el-option label="类型2" value="2"></el-option>
					<el-option label="类型3" value="3"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="权限代码">
				<el-input v-model="form.percode" placeholder="请输入权限代码" />
			</el-form-item>
			<el-form-item label="父节点ID">
				<el-input v-model="form.parentId" placeholder="请输入父节点ID" />
			</el-form-item>
			<el-form-item label="显示顺序">
				<el-input v-model="form.sort" placeholder="请输入显示顺序" />
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false" @close="cancle">取消</el-button>
				<el-button type="primary" @click="add">确定</el-button>
			</div>
		</template>
	</el-dialog>
	<!-- 表格 -->
	<div>
		<el-table ref="multipleTableRef" border :data="tableData" row-key="id" style="width: 100%"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column property="id" label="ID" />
			<el-table-column property="name" label="权限名称" />
			<el-table-column property="type" label="权限类型" />
			<el-table-column property="url" label="访问地址" />
			<el-table-column property="percode" label="权限代码" />
			<el-table-column property="parentId" label="父节点ID" />
			<el-table-column property="sort" label="显示顺序" />
			<el-table-column label="操作">
				<template #default='scope'>
					<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>

	<!-- 分页 -->
	<el-pagination v-model:current-page="formInline.pageNum" v-model:page-size="formInline.pageSize"
		:page-sizes="[5, 10, 15, 20]" :size="size" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" style="margin-top: 8px;" />
</template>

<script lang="ts" setup>
	import { onMounted, reactive, ref } from 'vue'
	import type { TableInstance } from 'element-plus'
	import axios from 'axios'
	import { ElMessage, ElMessageBox } from 'element-plus'

	// 行内表单
	const formInline = reactive({
		name: '',
		type: '',
		pageNum: 1,
		pageSize: 5
	})
	// 行内表单搜索效果
	const seek = () => {
		axios.get('http://localhost:8080/permission/page', {
			params: formInline
		})
			.then((resp) => {
				console.log(resp);
				total.value = resp.data.data.total;
				tableData.value = resp.data.data.list
			})
	}

	// 行内表单中新增编辑权限弹出框
	const dialogVisible = ref(false);
	const add = () => {
		// 新增和编辑共用一个接口，根据是否有id判断
		if (form.value.id) {
			// 编辑操作（假设后端提供put接口）
			axios.put(`http://localhost:8080/permission/${form.value.id}`, form.value)
				.then((resp) => {
					if (resp.data.code == 200) {
						ElMessage({
							type: 'success',
							message: '编辑成功',
						})
					} else {
						ElMessage({
							type: 'error',
							message: '编辑失败',
						})
					}
					dialogVisible.value = false;
					query();
				})
		} else {
			// 新增操作
			axios.post('http://localhost:8080/permission', form.value)
				.then((resp) => {
					if (resp.data.code == 200) {
						ElMessage({
							type: 'success',
							message: '添加成功',
						})
					} else {
						ElMessage({
							type: 'error',
							message: '添加失败',
						})
					}
					dialogVisible.value = false;
					query();
				})
		}
	}
	const title = ref('新增权限')
	// 编辑按钮打开框
	const edit = (row) => {
		dialogVisible.value = true;
		title.value = '编辑权限';
		// 深拷贝避免直接修改表格数据
		form.value = { ...row };
	}
	// 取消或关闭弹出框重置数据
	const cancle = () => {
		form.value = {
			id: '',
			name: "",
			type: '',
			url: '',
			percode: '',
			parentId: '',
			sort: '',
		}
	}
	// 新增编辑弹出框表单内容
	const form = ref({
		id: '',
		name: '',
		type: '',
		url: '',
		percode: '',
		parentId: '',
		sort: '',
	})

	// 表格
	const multipleTableRef = ref<TableInstance>()

	// 通过get请求获取数据
	const tableData = ref([]);
	const currentPage = ref(1);
	const pageSize = ref(5);
	const size = ref('default');
	const total = ref(0);

	const query = () => {
		axios.get('http://localhost:8080/permission/page', {
			params: formInline
		})
			.then((resp) => {
				console.log(resp);
				tableData.value = resp.data.data.list;
				total.value = resp.data.data.total;
			})
			.catch(error => {
				console.error('请求失败:', error);
				ElMessage.error('数据加载失败，请重试');
			})
	}
	onMounted(() => {
		query();
	})

	// 分页
	const handleSizeChange = (val) => {
		formInline.pageSize = val; // 修正：使用formInline的pageSize
		query();
	}
	const handleCurrentChange = (val) => {
		formInline.pageNum = val; // 修正：使用formInline的pageNum
		query();
	}
	// 删除功能
	const remove = (id) => {
		ElMessageBox.confirm(
			'此操作将永久删除该数据, 是否继续?',
			'提示',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				// 执行删除请求
				axios.delete(`http://localhost:8080/permission/${id}`)
					.then((resp) => {
						// 处理响应结果
						if (resp.data.code === 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败');
						}
						query()
					})
					.catch(error => {
						console.error('删除失败:', error);
						ElMessage.error('删除失败，请重试');
					});
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除'
				})
			})
	}
	// 批量删除功能
	// 批量删除功能（完全匹配后端接口）
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  console.log('复选框选择的数据', val);
  multipleSelection.value = val.map(item => item.id);
};

const removeAll = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据');
    return;
  }
  ElMessageBox.confirm(
    '此操作将永久删除选中的数据, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 手动构建查询字符串
    const params = new URLSearchParams();
    multipleSelection.value.forEach(id => params.append('ids', id));
    
    return axios.delete(`http://localhost:8080/permission?${params.toString()}`);
  })
  .then((resp) => {
    if (resp.data.code === 200) {
      ElMessage({
        message: '批量删除成功',
        type: 'success',
      });
    } else {
      ElMessage.error('批量删除失败: ' + (resp.data.message || '未知错误'));
    }
    query();
  })
  .catch(error => {
    if (error.response) {
      console.error('后端错误:', error.response.data);
      ElMessage.error('批量删除失败: ' + error.response.data.message);
    } else if (error !== 'cancel') {
      console.error('请求失败:', error);
      ElMessage.error('网络错误，批量删除失败');
    }
  });
};
</script>

<style>
	/* 面包屑样式 */
	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 15px;
		border-bottom: 1px solid #ddd;
	}


	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}
</style>